package com.nq.service.impl;

/**

 * 开发者----股牛网络

 * 联系TG：gncms

 */
/**
 * 开发者----股牛网络
 * 联系TG：gncms
 */
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nq.common.ServerResponse;
import com.nq.dao.AgentUserMapper;
import com.nq.dao.SiteTaskLogMapper;
import com.nq.pojo.*;
import com.nq.service.IAgentAgencyFeeService;
import com.nq.service.IAgentDistributionUserService;
import com.nq.service.IAgentUserService;
import com.nq.service.ISiteInfoService;
import com.nq.utils.KeyUtils;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.SymmetricCryptoUtil;
import com.nq.utils.redis.CookieUtils;
import com.nq.utils.redis.JsonUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.vo.agent.AgentInfoVO;
import com.nq.vo.agent.AgentSecondInfoVO;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("iAgentUserService")
public class AgentUserServiceImpl implements IAgentUserService {
    private static final Logger log = LoggerFactory.getLogger(AgentUserServiceImpl.class);


    @Autowired
    AgentUserMapper agentUserMapper;
    @Autowired
    SiteTaskLogMapper siteTaskLogMapper;


    @Autowired
    ISiteInfoService iSiteInfoService;

    @Autowired
    IAgentDistributionUserService iAgentDistributionUserService;

    @Autowired
    IAgentAgencyFeeService iAgentAgencyFeeService;


    public AgentUser getCurrentAgent(HttpServletRequest request) {
//        String loginToken = CookieUtils.readLoginToken(request, PropertiesUtil.getProperty("agent.cookie.name"));
        String loginToken = request.getHeader(PropertiesUtil.getProperty("agent.cookie.name"));
        if (StringUtils.isEmpty(loginToken)) {
            return null;
        }
        String agentJson = RedisShardedPoolUtils.get(loginToken);
        AgentUser agentUser = (AgentUser) JsonUtil.string2Obj(agentJson, AgentUser.class);
        if (agentUser ==null){
            return null;
        }

        return this.agentUserMapper.selectByPrimaryKey(agentUser.getId());
    }


    public AgentUser findByCode(String agentCode) {
        return this.agentUserMapper.findByCode(agentCode);
    }


    public ServerResponse login(String agentPhone, String agentPwd, String verifyCode, HttpServletRequest request) {
//        if (StringUtils.isBlank(verifyCode)) {
//            return ServerResponse.createByErrorMsg("验证码不能为空");
//        }
        String original = (String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");

//        if (!verifyCode.equalsIgnoreCase(original)) {
//            return ServerResponse.createByErrorMsg("验证码错误");
//        }

        if (StringUtils.isBlank(agentPhone) || StringUtils.isBlank(agentPwd)) {
            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");
        }
        agentPwd = SymmetricCryptoUtil.encryptPassword(agentPwd);
        AgentUser agentUser = this.agentUserMapper.login(agentPhone, agentPwd);
        if (agentUser == null) {
            return ServerResponse.createByErrorMsg("The user password is incorrect.");
        }

        if (agentUser.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("Login failed, your account has been locked！");
        }

        return ServerResponse.createBySuccess(agentUser);
    }


    public ServerResponse getAgentInfo(HttpServletRequest request) {
        String host = "";
        ServerResponse serverResponse = this.iSiteInfoService.getInfo();
        if (serverResponse.isSuccess()) {
            SiteInfo siteInfo = (SiteInfo) serverResponse.getData();
            if (StringUtils.isBlank(siteInfo.getSiteHost())) {
                return ServerResponse.createByErrorMsg("info host Not set up");
            }
            host = siteInfo.getSiteHost();
        }
        String loginToken = CookieUtils.readLoginToken(request, PropertiesUtil.getProperty("agent.cookie.name"));
        String agentJson = RedisShardedPoolUtils.get(loginToken);
        AgentUser agentUser = (AgentUser) JsonUtil.string2Obj(agentJson, AgentUser.class);
        if (agentUser ==null){
          return   ServerResponse.createByError("Please log in first.",null);
        }
        AgentUser dbuser = this.agentUserMapper.selectByPrimaryKey(agentUser.getId());
        AgentInfoVO agentInfoVO = assembleAgentInfoVO(dbuser, host);
        return ServerResponse.createBySuccess(agentInfoVO);
    }


    public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)) {
            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");
        }

        AgentUser agentUser = getCurrentAgent(request);
            if (agentUser ==null){
             return    ServerResponse.createByError("Please log in first.",null);
            }
        oldPwd = SymmetricCryptoUtil.encryptPassword(oldPwd);
        if (!oldPwd.equals(agentUser.getAgentPwd())) {
            return ServerResponse.createByErrorMsg("Incorrect password.");
        }

        agentUser.setAgentPwd(SymmetricCryptoUtil.encryptPassword(newPwd));
        int updateCount = this.agentUserMapper.updateByPrimaryKeySelective(agentUser);

        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("Successful modification");
        }
        return ServerResponse.createByErrorMsg("Modification Failed");
    }


    public ServerResponse addAgentUser(String agentName, String agentPwd, String agentRealName,
                                       String agentPhone, Integer parentId, String poundageScale,
                                       String deferredFeesScale, String receiveDividendsScale,
                                       String serviceUrl, HttpServletRequest request) {
        if (StringUtils.isBlank(agentName) ||
                StringUtils.isBlank(agentPwd) ||
                StringUtils.isBlank(agentRealName) ||
                StringUtils.isBlank(agentPhone)) {
            return ServerResponse.createByErrorMsg("The addition failed, and the parameters cannot be empty.");
        }

        AgentUser dbuser = this.agentUserMapper.findByName(agentName);
        if (dbuser != null) {
            return ServerResponse.createByErrorMsg("The addition failed, and the agent name already exists.");
        }

        AgentUser dbuser2 = this.agentUserMapper.findByPhone(agentPhone);
        if (dbuser2 != null) {
            return ServerResponse.createByErrorMsg("Failed to add, the mobile phone number already exists.");
        }

        // 当前代理
        AgentUser currAgentUser = getCurrentAgent(request);
        if (null == currAgentUser) {
            return ServerResponse.createByErrorMsg("Failed to add, the agent does not exist.");
        }
        // 当前代理等级
        int agentLevel = currAgentUser.getAgentLevel();
        if (agentLevel >= 1) {
            return ServerResponse.createByErrorMsg("Failed to add, The current agent enrollment is level 3 and does not allow the creation of subordinate agents.");
        }

        AgentUser agentUser = new AgentUser();
        agentUser.setAgentName(agentName);
        agentUser.setAgentPwd(SymmetricCryptoUtil.encryptPassword(agentPwd));
        agentUser.setAgentCode(KeyUtils.getAgentUniqueKey());
        agentUser.setAgentRealName(agentRealName);
        agentUser.setAgentPhone(agentPhone);
        agentUser.setAddTime(new Date());
        agentUser.setIsLock(Integer.valueOf(0));
        agentUser.setPoundageScale(new BigDecimal(poundageScale));
        agentUser.setDeferredFeesScale(new BigDecimal(deferredFeesScale));
        agentUser.setReceiveDividendsScale(new BigDecimal(receiveDividendsScale));
        agentUser.setTotalMoney(new BigDecimal(0));
        agentUser.setServiceUrl(serviceUrl);
        /*AgentUser currentAgent = getCurrentAgent(request);
        agentUser.setParentId(currentAgent.getId());
        agentUser.setParentName(currentAgent.getAgentName());*/
        AgentUser parentAgent = this.agentUserMapper.selectByPrimaryKey(parentId);
        if (parentId != null && parentId>0) {
            if (parentAgent != null) {
//                if(parentAgent.getAgentLevel()>=6){
//                    return ServerResponse.createByErrorMsg("Level 6 agents cannot add subordinates.");
//                }
                agentUser.setParentId(parentAgent.getId());
                agentUser.setParentName(parentAgent.getAgentName());
                agentUser.setAgentLevel(parentAgent.getAgentLevel()+1);
            } else {
                //总代理默认0级
                agentUser.setAgentLevel(Integer.valueOf(0));
                agentUser.setParentId(Integer.valueOf(0));
            }
        } else {
            //总代理默认0级
            agentUser.setAgentLevel(Integer.valueOf(0));
            agentUser.setParentId(Integer.valueOf(0));
        }

        int insertCount = 0;
        try {
            this.agentUserMapper.insert(agentUser);
            insertCount = agentUser.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (insertCount > 0) {
            if (parentAgent != null) {
                //分销用户数据处理
                recursiveSaveAgentDistributionUser(insertCount,parentId,parentAgent.getAgentLevel());
            }
            return ServerResponse.createBySuccessMsg("Save the agent user successfully.");
        }
        return ServerResponse.createByErrorMsg("Failed to add, please try again.");
    }

    @Override
    public ServerResponse agentList(String realName, String phone, int pageNum, int pageSize, Integer agentUserId, HttpServletRequest request) {

        Page<AgentUser> page = PageHelper.startPage(pageNum, pageSize);

        List<AgentUser> agentUsers = agentUserMapper.agentList(realName, phone, agentUserId);
        PageInfo pageInfo = new PageInfo(page);
        pageInfo.setList(agentUsers);
        return ServerResponse.createBySuccess(pageInfo);

    }

    //分销代理数据：循环添加
    public int recursiveSaveAgentDistributionUser(int agentId, int parentId,int level){
        int k = 0;
        int pId = parentId;
        for (int i = level; i >= 0; i--){
            AgentUser parentAgent = this.agentUserMapper.selectByPrimaryKey(pId);
            System.out.print("分销代理数据level="+i+"===parentid="+parentAgent.getParentId());
            //分销用户数据处理
            AgentDistributionUser agentDistributionUser = new AgentDistributionUser();
            agentDistributionUser.setAgentId(agentId);
            agentDistributionUser.setParentId(parentAgent.getId());
            agentDistributionUser.setParentLevel(parentAgent.getAgentLevel());
            agentDistributionUser.setAddTime(new Date());
            agentDistributionUser.setUpdateTime(new Date());
            iAgentDistributionUserService.insert(agentDistributionUser);

            if (parentAgent.getParentId()==null){
                pId = 0;
            }else{
                pId = parentAgent.getParentId();

            }
            k++;
        }
        return k;
    }


    public ServerResponse<PageInfo> getSecondAgent(int pageNum, int pageSize, HttpServletRequest request) {
        Page<AgentSecondInfoVO> page = PageHelper.startPage(pageNum, pageSize);
        AgentUser agentUser = getCurrentAgent(request);
        if (agentUser ==null){
        return     ServerResponse.createByError("Please log in first.",null);
        }
        //log.info("======test=======" + agentUser.getId().toString());
        List<AgentUser> agentUsers = this.agentUserMapper.getSecondAgent(agentUser.getId());
        /*
        List<AgentSecondInfoVO> agentSecondInfoVOS = Lists.newArrayList();
        for (AgentUser agentUser1 : agentUsers) {
            AgentSecondInfoVO agentSecondInfoVO = assembleAgentSecondInfoVO(agentUser1);
            agentSecondInfoVOS.add(agentSecondInfoVO);
        }*/
        PageInfo pageInfo = new PageInfo(page);
        pageInfo.setList(agentUsers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /*查询代理所有上级*/
    @Override
    public  List<AgentUser> getAgentSuperiorList(int agentId){
        return  this.agentUserMapper.getAgentSuperiorList(agentId);
    }

    public ServerResponse<PageInfo> listByAdmin(String realName, String phone, int pageNum, int pageSize, int id, HttpServletRequest request) {
        Page<AgentUser> page = PageHelper.startPage(pageNum, pageSize);

        this.agentUserMapper.listByAdmin(realName, phone, id);
        PageInfo pageInfo = new PageInfo(page);

        return ServerResponse.createBySuccess(pageInfo);
    }

    public ServerResponse add(AgentUser agentUser, HttpServletRequest request) {
        if (StringUtils.isBlank(agentUser.getAgentName()) ||
                StringUtils.isBlank(agentUser.getAgentPhone()) ||
                StringUtils.isBlank(agentUser.getAgentRealName()) ||
                StringUtils.isBlank(agentUser.getAgentPwd())) {
            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");
        }

        AgentUser pAgent = this.agentUserMapper.findByPhone(agentUser.getAgentPhone());
        if (pAgent != null) {
            return ServerResponse.createByErrorMsg("The mobile phone number already exists.");
        }

        AgentUser nameAgent = this.agentUserMapper.findByName(agentUser.getAgentName());
        if (nameAgent != null) {
            return ServerResponse.createByErrorMsg("The agent's name already exists.");
        }

        AgentUser dbAgent = new AgentUser();
        dbAgent.setAgentName(agentUser.getAgentName());
        dbAgent.setAgentPwd(SymmetricCryptoUtil.encryptPassword(agentUser.getAgentPwd()));
        dbAgent.setAgentPhone(agentUser.getAgentPhone());
        dbAgent.setAgentRealName(agentUser.getAgentRealName());
        dbAgent.setAddTime(new Date());
        dbAgent.setIsLock(Integer.valueOf(0));
        dbAgent.setServiceUrl(agentUser.getServiceUrl());
        dbAgent.setAgentCode(KeyUtils.getAgentUniqueKey());
        //AgentUser loginAgent = getCurrentAgent(request);
        if (agentUser.getParentId() != null) {
            AgentUser parentAgent = this.agentUserMapper.selectByPrimaryKey(agentUser.getParentId());
            if (parentAgent != null) {
                dbAgent.setParentId(parentAgent.getId());
                dbAgent.setParentName(parentAgent.getAgentName());
                dbAgent.setAgentLevel(parentAgent.getAgentLevel()+1);
            } else {
                //总代理默认0级
                dbAgent.setAgentLevel(Integer.valueOf(0));
                dbAgent.setParentId(Integer.valueOf(0));
            }
        }

        int insertCount = this.agentUserMapper.insert(dbAgent);
        if (insertCount > 0) {
            return ServerResponse.createBySuccessMsg("Successfully added the agent");
        }
        return ServerResponse.createByErrorMsg("Failed to add a proxy");
    }


    public ServerResponse update(AgentUser agentUser) {
        AgentUser dbAgent = new AgentUser();

        if (StringUtils.isNotBlank(agentUser.getAgentName())) {
            return ServerResponse.createByErrorMsg("Agent name cannot be changed");
        }

        dbAgent.setId(agentUser.getId());
        if (StringUtils.isNotBlank(agentUser.getAgentPwd())) {
            dbAgent.setAgentPwd(SymmetricCryptoUtil.encryptPassword(agentUser.getAgentPwd()));
        }
        if (StringUtils.isNotBlank(agentUser.getAgentRealName())) {
            dbAgent.setAgentRealName(agentUser.getAgentRealName());
        }
        if (StringUtils.isNotBlank(agentUser.getServiceUrl())) {
            dbAgent.setServiceUrl(agentUser.getServiceUrl());
        }
        if (StringUtils.isNotBlank(agentUser.getAgentPhone())) {
            AgentUser phoneAgent = this.agentUserMapper.findByPhone(agentUser.getAgentPhone());

            if (phoneAgent == null || phoneAgent.getId().equals(agentUser.getId())) {
                dbAgent.setAgentPhone(agentUser.getAgentPhone());
            } else {
                return ServerResponse.createByErrorMsg("The mobile phone number already exists, please change the mobile phone.");
            }
        }

        if (agentUser.getIsLock() != null) {
            dbAgent.setIsLock(agentUser.getIsLock());
        }

        if (agentUser.getParentId() != null) {
            AgentUser parentAgent = this.agentUserMapper.selectByPrimaryKey(agentUser.getParentId());
            if (parentAgent != null) {
                dbAgent.setParentId(parentAgent.getId());
                dbAgent.setParentName(parentAgent.getAgentName());
            }
        }

        int updateCount = this.agentUserMapper.updateByPrimaryKeySelective(dbAgent);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("Modify the agent successfully");
        }
        return ServerResponse.createByErrorMsg("Failed to modify the agent");
    }

    public int CountAgentNum() {
        return this.agentUserMapper.CountAgentNum();
    }


    private AgentSecondInfoVO assembleAgentSecondInfoVO(AgentUser agentUser) {
        AgentSecondInfoVO agentSecondInfoVO = new AgentSecondInfoVO();
        agentSecondInfoVO.setId(agentUser.getId());
        agentSecondInfoVO.setAgentCode(agentUser.getAgentCode());
        agentSecondInfoVO.setAgentName(agentUser.getAgentName());
        agentSecondInfoVO.setAgentPhone(agentUser.getAgentPhone());
        agentSecondInfoVO.setAgentRealName(agentUser.getAgentRealName());
        return agentSecondInfoVO;
    }

    private AgentInfoVO assembleAgentInfoVO(AgentUser agentUser, String host) {
        AgentInfoVO agentInfoVO = new AgentInfoVO();
        agentInfoVO.setId(agentUser.getId());
        agentInfoVO.setAgentName(agentUser.getAgentName());
        agentInfoVO.setAgentRealName(agentUser.getAgentRealName());
        agentInfoVO.setAgentPhone(agentUser.getAgentPhone());
        agentInfoVO.setAgentCode(agentUser.getAgentCode());
        agentInfoVO.setAddTime(agentUser.getAddTime());
        agentInfoVO.setIsLock(agentUser.getIsLock());
        agentInfoVO.setParentId(agentUser.getParentId());
        agentInfoVO.setParentName(agentUser.getParentName());
        agentInfoVO.setTotalMoney(agentUser.getTotalMoney());

        String pcUrl = host + PropertiesUtil.getProperty("site.pc.reg.url") + agentUser.getAgentCode();
        agentInfoVO.setPcUrl(pcUrl);
        String mUrl = host + PropertiesUtil.getProperty("site.m.reg.url") + agentUser.getAgentCode();
        agentInfoVO.setMUrl(mUrl);
        return agentInfoVO;
    }

    /*代理账户扣款*/
    @Transactional
    public ServerResponse updateAgentAmt(Integer agentId, Integer amt, Integer direction) {
        if (agentId == null || amt == null || direction == null) {
            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");
        }

        AgentUser agentUser = this.agentUserMapper.selectByPrimaryKey(agentId);
        if (agentUser == null) {
            return ServerResponse.createByErrorMsg("The agent does not exist");
        }

        BigDecimal totalMoney = agentUser.getTotalMoney();//扣除前金额
        BigDecimal back_amt = agentUser.getTotalMoney();//扣除后余额
        BigDecimal deduct_amt = new BigDecimal(amt);//扣除金额
        if (totalMoney==null){
            totalMoney = new BigDecimal(0);
        }
        if (direction.intValue() == 0) {

        } else if (direction.intValue() == 1) {
            if (totalMoney.compareTo(new BigDecimal(amt)) < 0) {
                return ServerResponse.createByErrorMsg("The deduction failed, and the total funds were insufficient.");
            }
            deduct_amt = deduct_amt.multiply(new BigDecimal(-1));
            back_amt = back_amt.subtract(new BigDecimal(amt));
        } else {
            return ServerResponse.createByErrorMsg("This action does not exist.");
        }

        //修改代理账户余额
        AgentUser user = new AgentUser();
        user.setId(agentUser.getId());
        user.setTotalMoney(deduct_amt);
        agentUserMapper.updateTotalMoney(user);
        //利润明细增加
        AgentAgencyFee agentAgencyFee = new AgentAgencyFee();
        agentAgencyFee.setAgentId(agentUser.getId());
        agentAgencyFee.setStatus(1);
        agentAgencyFee.setAymentType(2);
        agentAgencyFee.setBusinessId(0);
        agentAgencyFee.setFeeType(0);
        agentAgencyFee.setTotalMoney(deduct_amt);
        agentAgencyFee.setProfitMoney(new BigDecimal(amt.intValue()));
        agentAgencyFee.setRemarks("[Cash Withdrawal Expenditure] Cash Withdrawal Amount："+amt);
        iAgentAgencyFeeService.insert(agentAgencyFee);


        SiteTaskLog siteTaskLog = new SiteTaskLog();
        siteTaskLog.setTaskType("Administrator Modify Agent Amount");
        StringBuffer cnt = new StringBuffer();
        cnt.append("Administrator Modify Agent Amount - ")
                .append((direction.intValue() == 0) ? "Incoming payment" : "Deduction")
                .append(amt).append("USD");
        siteTaskLog.setTaskCnt(cnt.toString());

        StringBuffer target = new StringBuffer();
        target.append("agent id : ").append(agentUser.getId())
                .append("Total funds before revision = ").append(totalMoney)
                .append("Modified total funds = ").append(back_amt);
        siteTaskLog.setTaskTarget(target.toString());

        siteTaskLog.setIsSuccess(Integer.valueOf(0));
        siteTaskLog.setAddTime(new Date());

        int insertCount = this.siteTaskLogMapper.insert(siteTaskLog);
        if (insertCount > 0) {
            return ServerResponse.createBySuccessMsg("Successfully modified the funds");
        }
        return ServerResponse.createByErrorMsg("Failed to modify funds");
    }

    /*删除代理*/
    public ServerResponse delAgent(Integer agentId) {
        AgentUser dbAgent = this.agentUserMapper.selectByPrimaryKey(agentId);

        if (dbAgent == null) {
            return ServerResponse.createByErrorMsg("The agent does not exist, please operate normally.！");
        }

        int updateCount = this.agentUserMapper.deleteByPrimaryKey(agentId);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("Delete the agent successfully");
        }
        return ServerResponse.createByErrorMsg("Failed to delete the agent");
    }
}

